import { NextRequest, NextResponse } from 'next/server'
import prisma from '@/lib/prisma'
import { getUserIdFromRequest } from '@/lib/authUtils'

// Delete a specific course section
export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string; sectionId: string } }
): Promise<NextResponse> {
  try {
    const userId = await getUserIdFromRequest(request)
    if (!userId) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    // Verify course ownership
    const course = await prisma.vms_course.findFirst({
      where: {
        id: params.id,
        user_id: userId
      }
    })

    if (!course) {
      return NextResponse.json({ error: 'Course not found' }, { status: 404 })
    }

    // Verify section exists and belongs to the course
    const section = await prisma.vms_course_section.findFirst({
      where: {
        id: params.sectionId,
        course_id: params.id
      }
    })

    if (!section) {
      return NextResponse.json({ error: 'Section not found' }, { status: 404 })
    }

    // Delete the section
    await prisma.vms_course_section.delete({
      where: {
        id: params.sectionId
      }
    })

    return NextResponse.json({ message: 'Section deleted successfully' })
  } catch (error) {
    console.error('Error deleting course section:', error)
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    )
  }
}

// Update a specific course section
export async function PUT(request: Request, { params }: { params: { id: string; sectionId: string } }) {
  try {
    const body = await request.json();
    const { title, content, content_md, published } = body;
    
    // 构建更新数据对象
    const updateData: any = {
      title,
      content,
      content_md,
    };

    // 仅当 published 字段存在时才添加到更新数据中
    if (published !== undefined) {
      updateData.published = published;
    }

    const updatedSection = await prisma.vms_course_section.update({
      where: { id: params.sectionId },
      data: updateData,
    });

    // 直接返回，无需字段映射
    return NextResponse.json(updatedSection);
  } catch (error) {
    console.error('Error updating section:', error);
    return NextResponse.json(
      { error: 'Failed to update section' },
      { status: 500 }
    );
  }
}
// Get a specific course section
export async function GET(
  request: NextRequest,
  { params }: { params: { id: string; sectionId: string } }
): Promise<NextResponse> {
  try {
    const userId = await getUserIdFromRequest(request)
    if (!userId) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    // Verify course ownership
    const course = await prisma.vms_course.findFirst({
      where: {
        id: params.id,
        user_id: userId
      }
    })

    if (!course) {
      return NextResponse.json({ error: 'Course not found' }, { status: 404 })
    }

    // Get the section
    const section = await prisma.vms_course_section.findFirst({
      where: {
        id: params.sectionId,
        course_id: params.id
      },
      include: {
        source_copy: true
      }
    })

    if (!section) {
      return NextResponse.json({ error: 'Section not found' }, { status: 404 })
    }

    return NextResponse.json(section)
  } catch (error) {
    console.error('Error fetching course section:', error)
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    )
  }
}